import pymysql
from common.logger import log
from settings import ENV,DBsql
from sshtunnel  import SSHTunnelForwarder





class MysqlAuto(object):
    #如需使用ssh通道请调用ssg_server


    def __del__(self):
        #实例化对象被释放时执行,关闭游标和连接，并记录日志
        self.cursor.close()
        self.connection.close()
        log.info("数据库关闭成功")

    def __init__(self):

        #创建连接和游标，并记录日志
        self.connection  = pymysql.connect(host = DBsql.host,user = DBsql.user, passwd = DBsql.password,port = DBsql.port,charset = DBsql.charset,database = DBsql.database)
        self.cursor = self.connection.cursor()
        log.info("成功连接数据库")

    def execute(self,sql_list):

        #执行sql语句列表
        try:
            for i in sql_list:
                log.info(f"Executing SQL statement: {i}")
                self.cursor.execute(i)
                log.debug(self.cursor.fetchall())
            self.connection.commit()
            return self.cursor.fetchall()
        except Exception as e :

            #捕获异常并记录日志
            log.error(f"sql执行错误，异常信息：{e}")
            raise e



if __name__ == '__main__':
    MysqlAuto().execute(["select * from account"])